//  MineAblumVedio.m
//  XJMTechnician
//  Created by Mr.hu on 2017/10/17.
//  Copyright © 2017年 Mr.hu. All rights reserved.

#import "MineAblumVedio.h"
#import "MineVideoUploading.h"
#import "QiniuSDK.h"
#import "QN_GTM_Base64.h"
#import "QNConfiguration.h"
#import "QiniuLoad.h"
#import "PhotoSolution-Swift.h"
#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import "PhotoCollectCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "LxGridViewFlowLayout.h"
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZLocationManager.h"
#import "TestViewController.h"
#import "QiniuLoad.h"
#import "UploadVideoViewController.h"
#import "PhotoModel.h"
#import "Pics.h"
#import "PhotoCollectCell.h"
@interface MineAblumVedio ()<UIScrollViewDelegate,LQPhotoPickerViewDelegate,TZImagePickerControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UINavigationControllerDelegate,PhotoSolutionDelegate,LGPhotoPickerBrowserViewControllerDelegate, LGPhotoPickerBrowserViewControllerDataSource, PhotoCollectCellDelegate>
{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    
    NSMutableArray *_uploadImages;
    NSMutableArray *_allImageItem;
    BOOL _isSelectOriginalPhoto;
    
    CGFloat _itemWH;
    CGFloat _margin;
    PhotoModel *_model;
}

@property (strong, nonatomic) UIScrollView * scrollview;
@property (nonatomic,copy) NSString * PhotoMut_Url;
@property (nonatomic,strong)  NSMutableArray * image_pics;

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *layout;
@property (strong, nonatomic) CLLocation *location;
@property (nonatomic,strong)  NSMutableArray * delete_ArrId;

@end

@implementation MineAblumVedio
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
    }
    return _imagePickerVc;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的相册";
    
    _selectedAssets = [NSMutableArray array];
    _uploadImages = [NSMutableArray array];
    
    [self addRightBtn:[UIImage imageNamed:@"shipin"] Action:@selector(VideoUploadingMeth)];
    
    [self configCollectionView];
    
    [self getList];
}

- (void)configCollectionView {
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    CGFloat rgb = 244 / 255.0;
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    self.view.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _collectionView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[PhotoCollectCell class] forCellWithReuseIdentifier:@"PhotoCollectCell"];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    _margin = 4;
    _itemWH = (self.view.tz_width - 2 * _margin - 4) / 3 - _margin;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = _margin;
    [self.collectionView setCollectionViewLayout:_layout];
    //判断iphoneX的情况
    self.collectionView.frame = CGRectMake(0, 0, self.view.tz_width,ScreenHeight-150);
}

- (void)SureUploadMeth{
    
    if (_selectedPhotos.count > 0) {
        [LoadingView showCircleView: self.view];
        [XJHttpClass ReceiveQiniuTokenFinishblock:^(id response, NSString *errStr) {
            if (errStr) {
                [XJToolClass tipAnimationWith:errStr];
            }else{
                NSDictionary * datadict = response[@"data"];
                NSString * qiniu_token = datadict[@"upToken"];
                
                [QiniuLoad uploadImageToQNFilePath:_selectedPhotos token:qiniu_token success:^(NSString *reslut) {
                    
                    [LoadingView hide];
                    //type 1:上传图片 2：上传视频
                    [XJHttpClass teachUploadPhotoVideotoken:[XJToolClass getToken] type:@"1" pics:reslut videos:nil andFinishblock:^(id response, NSString *errStr) {
                        
                        if (errStr) {
                            [XJToolClass tipAnimationWith:errStr];
                        }else{
                            [self.navigationController popViewControllerAnimated:YES];
                            [XJToolClass tipAnimationWith:@"上传成功!"];
                        }
                    }];
                    
                } failure:^(NSString *error) {
                    NSLog(@"error:%@",error);
                }];
            }
        }];
    }else{
        [XJToolClass tipAnimationWith:@"请选择照片！"];
    }
}

- (void)getList
{
    _selectedPhotos = [NSMutableArray array];
    _allImageItem = [NSMutableArray array];
    [XJHttpClass TeachReceiveMineAlbumInformationToken:[XJToolClass getToken] andFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            [PhotoModel mj_setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data": @"PhotoData",
                         @"videos" : @"Videos"
                         };
            }];
            _model = [PhotoModel mj_objectWithKeyValues:response];
            if (_model.data.pics.count) {
                [_selectedPhotos addObjectsFromArray:_model.data.pics];
                for (NSInteger i = 0; i < _model.data.pics.count; i ++) {
                    Pics *pics = _model.data.pics[i];
                    LGPhotoPickerBrowserPhoto *photo = [[LGPhotoPickerBrowserPhoto alloc] init];
                    photo.photoURL = [NSURL URLWithString:pics.pic_url];
                    [_allImageItem addObject:photo];
                }
            }
            [_collectionView reloadData];
        }
    }];
}


- (void)VideoUploadingMeth{
    UploadVideoViewController *controller = [[UploadVideoViewController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PhotoCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCollectCell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[PhotoCollectCell alloc] init];
    }
    
    cell.indexPath = indexPath;
    cell.delegate = self;
    if (indexPath.row == _selectedPhotos.count) {
        cell.isAdd = YES;
    } else {
        cell.isAdd = NO;
        if (_selectedPhotos.count > 0) {
            Pics *pics = _selectedPhotos[indexPath.row];
            cell.pics = pics;
        }
    }
    
    return cell;
}

- (void)PhotoCollectCellDeleteImage:(PhotoCollectCell *)cell pic:(Pics *)pic
{
    NSString *deleteId = pic.attch_id;
    [XJHttpClass TeachDeleteMineAlbumInformationToken:[XJToolClass getToken] attch_id: deleteId andFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            [XJToolClass tipAnimationWith:@"删除成功！"];
            [self getList];
        }
    }];
}

- (void)PhotoCollectCellShowImage:(PhotoCollectCell *)cell index:(NSInteger)index
{
    LGPhotoPickerBrowserViewController *BroswerVC = [[LGPhotoPickerBrowserViewController alloc] init];
    BroswerVC.delegate = self;
    BroswerVC.dataSource = self;
    BroswerVC.showType = LGShowImageTypeImageURL;
    BroswerVC.currentIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:BroswerVC animated:YES completion:nil];
}

- (void)PhotoCollectCellAddImage:(PhotoCollectCell *)cell
{
    [self addImages];
}

//- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (_allImageItem && _allImageItem.count == 0) {
//        return;
//    }
//
//    LGPhotoPickerBrowserViewController *BroswerVC = [[LGPhotoPickerBrowserViewController alloc] init];
//    BroswerVC.delegate = self;
//    BroswerVC.dataSource = self;
//    BroswerVC.showType = LGShowImageTypeImageURL;
//    NSInteger index = indexPath.row;
//    BroswerVC.currentIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
//    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:BroswerVC animated:YES completion:nil];
//}

- (NSInteger)photoBrowser:(LGPhotoPickerBrowserViewController *)photoBrowser numberOfItemsInSection:(NSUInteger)section {
    
    return _allImageItem.count;
}

- (id<LGPhotoPickerBrowserPhoto>)photoBrowser:(LGPhotoPickerBrowserViewController *)pickerBrowser photoAtIndexPath:(NSIndexPath *)indexPath{
    return [_allImageItem objectAtIndex:indexPath.item];
}

#pragma mark - LxGridViewDataSource

///// 以下三个方法为长按排序相关代码
//- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
//    return indexPath.item < _selectedPhotos.count;
//}
//
//- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
//    return (sourceIndexPath.item < _selectedPhotos.count && destinationIndexPath.item < _selectedPhotos.count);
//}
//
//- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
//    UIImage *image = _selectedPhotos[sourceIndexPath.item];
//    [_selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
//    [_selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
//
//    id asset = _selectedAssets[sourceIndexPath.item];
//    [_selectedAssets removeObjectAtIndex:sourceIndexPath.item];
//    [_selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
//
//    [_collectionView reloadData];
//}

#pragma mark - TZImagePickerController


- (void)pickerCancel
{
    
}


- (void)returnImages:(NSArray<UIImage *> *)images
{
    [_uploadImages removeAllObjects];
    [_uploadImages addObjectsFromArray:images];
    [self getToken];
}

#pragma mark -- 上传图片
- (void)uploadImageWithToken:(NSString *)token
{
    [SVProgressHUD show];
    NSMutableArray *urls = [NSMutableArray array];
    for (NSInteger i = 0; i < _uploadImages.count; i ++) {
        UIImage *image = _uploadImages[i];
        if (image.size.width > 1000 || image.size.height > 1000) {
            image = [self image:image scaledToSize:1000];
        }
        NSData *imageData = UIImagePNGRepresentation(image);
        NSString *filename = [NSString fileKey];
        QNUploadManager *upManager = [[QNUploadManager alloc] init];
        [upManager putData:imageData key:filename token:token
                  complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      NSLog(@"key:%@",resp[@"key"]);
                      if (info.isOK) {
                          [urls addObject:[NSString stringWithFormat:@"%@/%@",kQiniuBaseUrl,resp[@"key"]]];
                      }else {
                          [SVProgressHUD dismiss];
                          [XJToolClass tipAnimationWith:info.error.localizedDescription];
                      }
                      if (urls.count == _uploadImages.count) {
                          dispatch_async(dispatch_get_main_queue(), ^{
                              [SVProgressHUD dismiss];
                          });
                          NSString *imageUrl = [urls componentsJoinedByString:@","];
                          [self updateImageUrlStr:imageUrl];
                      }
                  } option:[QNUploadOption defaultOptions]
         ];
    }
}

#pragma mark -- 更新图片
- (void)updateImageUrlStr:(NSString *)urlStr
{
    [XJHttpClass teachUploadPhotoVideotoken:[XJToolClass getToken] type:@"1" pics:urlStr videos:nil andFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            [XJToolClass tipAnimationWith:@"上传成功!"];
            [self getList];
        }
    }];
}

#pragma mark -- 获取token
- (void)getToken
{
    [XJHttpClass ReceiveQiniuTokenFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            NSDictionary * datadict = response[@"data"];
            NSString * qiniu_token = datadict[@"upToken"];
            
            [self uploadImageWithToken:qiniu_token];
        }
    }];
}

- (void)addImages
{
    PhotoSolution *photoSolution = [[PhotoSolution alloc] init];
    photoSolution.customization.navigationBarTextColor = kthemeColor;
    photoSolution.customization.markerColor = kthemeColor;
    photoSolution.customization.navigationBarBackgroundColor = kthemeColor;
    photoSolution.customization.titleForAlbum = @"相册";
    photoSolution.customization.settingButtonTextForPhotoAccess = @"设置";
    photoSolution.customization.cancelButtonTextForPhotoAccess = @"取消";
    photoSolution.customization.settingButtonTextForCameraAccess = @"设置";
    photoSolution.customization.cancelButtonTextForCameraAccess = @"取消";
    photoSolution.customization.returnImageSize = ReturnImageSizeCompressed;
    photoSolution.customization.statusBarColor = StatusBarColorBlack;
    photoSolution.delegate = self;
    [self presentViewController:[photoSolution getPhotoPickerWithMaxPhotos:9] animated:YES completion:nil];
}


#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(CLLocation *location, CLLocation *oldLocation) {
        weakSelf.location = location;
    } failureBlock:^(NSError *error) {
        weakSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}


#pragma mark - UIActionSheetDelegate

//- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//    if (buttonIndex == 0) { // take photo / 去拍照
//        [self takePhoto];
//    } else if (buttonIndex == 1) {
//        [self pushTZImagePickerController];
//    }
//}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }
}


#pragma mark - Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    Pics *pic = _selectedPhotos[sender.tag];
    NSString *deleteId = pic.attch_id;
        [XJHttpClass TeachDeleteMineAlbumInformationToken:[XJToolClass getToken] attch_id: deleteId andFinishblock:^(id response, NSString *errStr) {
            if (errStr) {
                [XJToolClass tipAnimationWith:errStr];
            }else{
                [XJToolClass tipAnimationWith:@"删除成功！"];
                [self getList];
            }
        }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

// 放大缩小图片
- (UIImage *)image:(UIImage *)image scaledToSize:(CGFloat)maxWidth;
{
    CGFloat w = (NSInteger)image.size.width;
    CGFloat h = (NSInteger)image.size.height;
    
    CGSize size = CGSizeZero;
    
    if (w < maxWidth && h < maxWidth) {
        size = CGSizeMake(w, h);
    }else {
        if (w > h) {
            size = CGSizeMake(maxWidth, (NSInteger)(h / w * maxWidth));
        }else{
            size = CGSizeMake((NSInteger)((w / h) * maxWidth), maxWidth);
        }
    }
    
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0,size.width,size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

@end
